<template>
  <!-- 编辑 -->
  <div>
    <el-dialog
      v-if="visible"
      v-el-drag-dialog
      :title="type==='edit'?'编辑客户':'审核客户'"
      :visible.sync="visible"
      width="70%"
      class="csmDialog"
      :append-to-body="true"
      @closed="reset"
    >
      <el-tabs v-model="activeTabName" @tab-click="handleClick">
        <el-tab-pane name="customer">
          <span slot="label"><i class="el-icon-user" /> 客户信息</span>
          <div class="addCsmDialog">
            <el-form v-show="activeTabName === 'customer'" ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="110px">
              <el-collapse v-model="activeNames" class="collapse">
                <el-collapse-item title="基本信息" name="1">
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="客户类型:" prop="csmType">
                        <el-select v-model="temp.csmType" :disabled="!(temp.isEdit&&temp.isEdit===1)" placeholder="请选择" @change="changeCsmType">
                          <el-option
                            v-for="item in csmTypeMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="户号:" prop="csmCode">
                        <el-input v-model.trim="temp.csmCode" :maxlength="20" placeholder="" clearable disabled />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="客户名称:" prop="csmName">
                        <el-input v-model.trim="temp.csmName" :maxlength="20" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="用气性质" prop="subType">
                        <el-select v-model="temp.subType" placeholder="请选择" @change="subTypeChange">
                          <el-option
                            v-for="item in subTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="客户类别:">
                        <el-select v-model="temp.gasNature" clearable placeholder="请选择">
                          <el-option
                            v-for="item in cardTypeAllList"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="开户电话" prop="openAccountPhone">
                        <el-input v-model.trim="temp.openAccountPhone" clearable @blur="verifyPhone(temp.openAccountPhone)" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="备注" prop="remark">
                        <el-input v-model="temp.remark" type="textarea" :rows="1" maxlength="255" show-word-limit />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="实名认证信息" name="2">
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="身份证姓名:" prop="sfzName">
                        <el-input v-model.trim="temp.sfzName">
                        <!-- <el-button slot="append" class="append-search">读卡</el-button> -->
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="身份证号:" prop="sfzh">
                        <el-input v-model.trim="temp.sfzh" clearable @input="inputSfzh(temp.sfzh)" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="身份证地址:" prop="sfzAddress">
                        <el-input v-model.trim="temp.sfzAddress" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item v-if="temp.csmType === 2&&((temp.subType!==2&&realNameConfig && (realNameConfig!==4 && realNameConfig!==1)) || (temp.subType===2&& realNameConfig && (realNameConfig===2 || realNameConfig===3)))" title="营业执照信息" name="3">
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="证件号码:" prop="zzbh">
                        <el-input v-model.trim="temp.zzbh" :maxlength="20" @change="zzbhChange" @blur="(value)=>searchCsmgroup(value)" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <div v-show="tipsShow" class="group-tips">该营业执照下已存在{{ groupCsmTotal }}名客户，点击可查看<el-link type="primary" :underline="false" @click="viewCsm()">相关客户</el-link>信息</div>
                <!-- <el-row :gutter="16" class="row-box">
                  <el-col :span="24">
                    <el-form-item label="证件图片:">
                      <el-upload
                        action="#"
                        list-type="picture-card"
                        :file-list="fileList"
                        :auto-upload="false"
                        multiple
                        :on-change="uploadChange"
                      >
                        <i slot="default" class="el-icon-plus" />
                        <div slot="file" slot-scope="{file}">
                          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                          <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                              <i class="el-icon-zoom-in" />
                            </span>
                            <span
                              v-if="!disabled"
                              class="el-upload-list__item-delete"
                              @click="handleRemove(file)"
                            >
                              <i class="el-icon-delete" />
                            </span>
                          </span>
                        </div>
                      </el-upload>
                      <el-dialog :visible.sync="dialogVisible" append-to-body>
                        <img width="100%" :src="dialogImageUrl" alt="">
                      </el-dialog>
                    </el-form-item>
                  </el-col>
                </el-row> -->
                </el-collapse-item>

                <el-collapse-item title="配送地址信息" name="4">
                  <div style="width: 100%;">
                    <div v-for="(item, index2) in temp.addressItems" :key="index2" class="csminfoBox">
                      <el-row :gutter="16">
                        <el-col :span="8">
                          <el-form-item label="联系人名称:" :prop="'addressItems.'+index2+'.contact'" :rules="rules.contact">
                            <el-input v-model.trim="item.contact" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="联系人电话:" :prop="'addressItems.'+index2+'.csmPhone'" :rules="rules.csmPhone">
                            <el-input v-model.trim="item.csmPhone" @blur="verifyCsmPhone(item.csmPhone)" @change="(value)=>crmPhoneChange(value, item.rowId, index2)" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="省市区:" :prop="'addressItems.'+index2+'.area'" :rules="rules.area">
                            <el-cascader v-if="item.area" :ref="'cascader'+index2" :key="item['cascader'+index2]" v-model="item.area" :props="addressProps" clearable style="width: 100%;" @visible-change="visibleChange" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="16">
                          <el-form-item label="详细地址:" :prop="'addressItems.'+index2+'.csmAddress'" :rules="rules.csmAddress">
                            <div style="display: flex;">
                              <!-- <el-input v-model.trim="item.csmAddress" :maxlength="50" style="width: 85%;" /> -->
                              <el-autocomplete
                                ref="suggestionInput"
                                v-model="item.csmAddress"
                                v-scrollLoad="getLoad"
                                :maxlength="50"
                                :debounce="300"
                                popper-class="address-autocomplete"
                                :fetch-suggestions="(queryString, cb) => queryAddressSearch(queryString, cb, index2)"
                                placeholder="请输入联系地址"
                                :trigger-on-focus="false"
                                disabled
                                @select="(value) => handleSelect(value, index2)"
                                @change="(value) => csmAddressChange(index2)"
                              />
                              <el-button type="primary" style="width: 15%;" @click="location(item,index2)">定位</el-button>
                            </div>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="门牌号:" :prop="'addressItems.'+index2+'.doorplate'" :rules="rules.doorplate">
                            <el-input v-model.trim="item.doorplate" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="楼层:" :prop="'addressItems.'+index2+'.csmFloor'" :rules="rules.csmFloor">
                            <el-input v-model.trim="item.csmFloor" type="number" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="所属机构:" :prop="'addressItems.'+index2+'.orgSNNo'" :rules="rules.orgSNNo">
                            <el-tree-select
                              v-model="item.orgSNNo"
                              :clearable="false"
                              class="tree-select"
                              :popover-width="360"
                              :select-params="{
                                clearable: true,
                                placeholder: '请选择',
                              }"
                              :tree-params=" {
                                'expand-on-click-node': false,
                                'highlight-current': true,
                                'filterable': true,
                                props:{
                                  value:'orgSNNo',
                                  label: 'orgName',
                                  disabled: 'disabled',
                                },
                                data: treeData
                              }"
                              @node-click="(value)=> selectTreeChange(value, index2)"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <div class="bottomBtn">
                            <div v-show="item.sp1 >>1 & 1 === 1" style="margin-right: 10px; color: red;">一户一码地址</div>
                            <div v-if="index2===temp.addressItems.length-1" class="btn" @click="addCsminfo(index2)">新增</div>
                            <div v-if="temp.addressItems.length>1&&!(item.sp1 >>1 & 1 === 1)" class="btn danger" @click="removeCsminfo(index2)">移除</div>
                            <div class="btn">
                              <span>默认地址</span>
                              <el-switch v-model="item.isMain" @change="(value)=>isMainChange(value,item.csmPhone,index2)" />
                            </div>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="话务联系人信息" name="5">
                  <el-button v-if="temp.phoneItems.length===0" type="primary" class="addCardBtn" @click="addLinkMan">新增</el-button>
                  <div v-for="(item, index2) in temp.phoneItems" :key="index2" class="csminfoBox">
                    <el-row :gutter="16">
                      <el-col :span="8">
                        <el-form-item label="联系人名称:" :prop="'phoneItems.'+index2+'.contact'" :rules="rules.contact">
                          <el-input v-model.trim="item.contact" :disabled="item.disabled" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="联系电话:" :prop="'phoneItems.'+index2+'.csmPhone'" :rules="rules.csmPhone">
                          <el-input v-model.trim="item.csmPhone" :disabled="item.disabled" :maxlength="20" @change="(value)=>phoneChange(value,index2)" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-button v-show="temp.phoneItems.length>1 && !item.disabled" type="danger" @click="removeLinkMan(index2)">
                          删除
                        </el-button>
                        <el-button v-show="index2===temp.phoneItems.length-1" type="primary" @click="addLinkMan">
                          添加
                        </el-button>
                      </el-col>
                    </el-row>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="开户信息" name="6">
                  <el-row v-if="temp.newType !== 1" :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="开户类型:" prop="newType">
                        <el-select v-model="temp.newType" placeholder="请选择">
                          <el-option
                            v-for="item in newTypeMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="客户来源:" prop="newFrom">
                        <el-select v-model="temp.newFrom" placeholder="请选择">
                          <el-option
                            v-for="item in customerFromPlatMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="销售人员:" prop="salesmanName">
                        <el-input v-model="temp.salesmanName" readonly>
                          <el-button v-if="!temp.salesmanName" slot="append" class="append-search" @click="openSalesman">获取</el-button>
                          <el-button v-else slot="append" class="append-search" :disabled="!((userInfo.utype & 4) > 0&&(userInfo.utype & 64) > 0) && (userInfo.utype & 1) === 0" @click.prevent="clearSalesman">清除</el-button>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="开户日期:" prop="createTime">
                        <el-date-picker
                          v-model="temp.createTime"
                          placeholder="选择日期"
                          style="width: 100%;"
                          :clearable="false"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="是否自提:" prop="isPickUp">
                        <el-select v-model="temp.isPickUp" placeholder="请选择">
                          <el-option
                            v-for="(value, key) in isPickUpMap"
                            :key="key"
                            :label="value"
                            :value="Number(key)"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="合同号:" prop="contractNumber">
                        <el-input v-model.trim="temp.contractNumber" :maxlength="30" @input="temp.contractNumber=temp.contractNumber.replace(/[^\d]/g, '')" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="支付方式:" prop="defaultPaymentMethod">
                        <el-select v-model="temp.defaultPaymentMethod" placeholder="请选择" @change="paymentMethodChange">
                          <el-option
                            v-for="item in paymentMethodMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="结款方式:" prop="settlementType">
                        <el-select v-model="temp.settlementType" placeholder="请选择" @change="settlementTypeChange">
                          <el-option
                            v-for="item in settlementTypeMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <div v-else>
                    <el-row :gutter="16" class="row-box">
                      <el-col :span="8">
                        <el-form-item label="开户类型:" prop="newType">
                          <el-select v-model="temp.newType" placeholder="请选择">
                            <el-option
                              v-for="item in newTypeMap"
                              :key="item.value"
                              :label="item.desc"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <div>
                      <el-row v-for="(item, index2) in goodsList" :key="index2" :gutter="16" class="row-box">
                        <el-col :span="8">
                          <el-form-item label="气瓶类型:">{{ item.goodsName }}</el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="气瓶数量:" prop="goodsCount">
                            <el-input-number v-model="item.goodsCount" :controls="false" :min="0" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <el-row :gutter="16" class="row-box">
                      <el-col :span="8">
                        <el-form-item label="客户来源:" prop="newFrom">
                          <el-select v-model="temp.newFrom" placeholder="请选择">
                            <el-option
                              v-for="item in customerFromPlatMap"
                              :key="item.value"
                              :label="item.desc"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="开户日期:" prop="createTime">
                          <el-date-picker
                            v-model="temp.createTime"
                            placeholder="选择日期"
                            style="width: 100%;"
                            :clearable="false"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="是否自提:" prop="isPickUp">
                          <el-select v-model="temp.isPickUp" placeholder="请选择">
                            <el-option
                              v-for="(value, key) in isPickUpMap"
                              :key="key"
                              :label="value"
                              :value="Number(key)"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="合同号:" prop="contractNumber">
                          <el-input v-model.trim="temp.contractNumber" :maxlength="30" @input="temp.contractNumber=temp.contractNumber.replace(/[^\d]/g, '')" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="支付方式:" prop="defaultPaymentMethod">
                          <el-select v-model="temp.defaultPaymentMethod" placeholder="请选择" @change="paymentMethodChange">
                            <el-option
                              v-for="item in paymentMethodMap"
                              :key="item.value"
                              :label="item.desc"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="结款方式:" prop="settlementType">
                          <el-select v-model="temp.settlementType" placeholder="请选择" @change="settlementTypeChange">
                            <el-option
                              v-for="item in settlementTypeMap"
                              :key="item.value"
                              :label="item.desc"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="证件信息(点击展开更多可填项)" name="7">
                  <el-button v-if="temp.cardItems.length===0|| (temp.cardItems.length>0&&!temp.cardItems.includes(item=>item.cardType===7))" type="primary" class="addCardBtn" @click="addCardItems">新增</el-button>
                  <div style="width: 100%;">
                    <div v-for="(item, index2) in temp.cardItems" v-show="item.cardType!==7" :key="index2" class="csminfoBox">
                      <el-row :gutter="16" class="row-box">
                        <el-col :span="8">
                          <el-form-item label="证件类型:" prop="cardType">
                            <el-select v-model="item.cardType" placeholder="请选择" @visible-change="(value)=>changeCardType(value,index2)">
                              <el-option
                                v-for="item2 in cardTypes"
                                :key="item2.value"
                                :label="item2.desc"
                                :value="item2.value"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="证件编号:" prop="cardNo">
                            <el-input v-model.trim="item.cardNo" :maxlength="20" placeholder="" @change="(value)=>cardNoChange(value, item.cardType)" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label-width="0">
                            <el-button v-if="temp.cardItems.length>1" type="danger" @click="removeCardItems(index2)">移除</el-button>
                            <el-button v-if="index2===temp.cardItems.length-1" type="primary" @click="addCardItems">新增</el-button>
                          </el-form-item>
                        </el-col>
                        <el-col v-if="item.cardType === 4" :span="8">
                          <el-form-item label="证件名称:" prop="cardNo">
                            <el-input v-model.trim="temp.licenseName" placeholder="" />
                          </el-form-item>
                        </el-col>
                        <el-col v-if="item.cardType === 4" :span="8">
                          <el-form-item label="法人代表:" prop="cardNo">
                            <el-input v-model.trim="temp.licenseUserName" placeholder="" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="16" class="row-box">
                        <el-col :span="24">
                          <el-form-item label="证件图片:">
                            <el-upload
                              action="#"
                              :data="item.qiniuData"
                              :before-upload="(file)=>beforeUpload(file, index2)"
                              list-type="picture-card"
                              :file-list="item.fileList"
                              :limit="limit"
                              :on-exceed="handleExceed"
                              :http-request="(e)=>uploadToQiNiu(e, index2)"
                              multiple
                              accept="image/jpeg, image/jpg, image/png"
                            >
                              <i slot="default" class="el-icon-plus" />
                              <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                <span class="el-upload-list__item-actions">
                                  <span
                                    class="el-upload-list__item-preview"
                                    @click="handlePictureCardPreview(file)"
                                  >
                                    <i class="el-icon-zoom-in" />
                                  </span>
                                  <span
                                    v-if="!disabled"
                                    class="el-upload-list__item-delete"
                                    @click="handleRemove2(file, index2)"
                                  >
                                    <i class="el-icon-delete" />
                                  </span>
                                </span>
                              </div>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible" append-to-body>
                              <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-collapse-item>
                <el-collapse-item v-if="temp.groupCode" title="客户组信息" name="3">
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="客户组号:" prop="groupCode">
                        <el-input v-model.trim="temp.groupCode" :disabled="true" :maxlength="20" style="width: 220px;">
                          <!-- <el-button slot="append" class="append-search" :disabled="temp.csmStatus===1" @click.prevent="getGroupcode">获取</el-button> -->
                        </el-input>
                        <!-- <el-button class="append-search" style="border-color: #01999F;" :disabled="temp.csmStatus===1" @click.prevent="chooseGroup">选择</el-button> -->
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="组名称:" prop="groupName">
                        <el-input v-model.trim="temp.groupName" clearable :disabled="true" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="组类型:" prop="groupType">
                        <el-select v-model="temp.groupType" placeholder="请选择" :disabled="true">
                          <el-option
                            v-for="item in groupTypeMap"
                            :key="item.value"
                            :label="item.desc"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="联系人:" prop="groupContact">
                        <el-input v-model.trim="temp.groupContact" :maxlength="20" style="width: 220px;" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="联系电话:" prop="groupContactPhone">
                        <el-input v-model.trim="temp.groupContactPhone" :maxlength="11" style="width: 220px;" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <!-- <div class="bottomBtn">
                    <div class="btn">
                      <span>关联组</span>
                      <el-switch v-model="relevanceGroup" @change="(value)=>relevanceGroupChange(value)" />
                    </div>
                  </div> -->
                </el-collapse-item>
                <el-collapse-item title="其他信息(点击展开更多可填项)" name="8">
                  <el-row :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="使用权费:" prop="strSpare1">
                        <el-input-number v-model.trim="temp.strSpare1" :min="0" :max="999999999" :precision="2" :controls="false" style="width: 100%;" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="备用字段2:" prop="strSpare2">
                        <el-input v-model.trim="temp.strSpare2" :maxlength="30" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="备用字段3:" prop="strSpare3">
                        <el-input v-model.trim="temp.strSpare3" :maxlength="50" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="备用字段4:" prop="strSpare4">
                        <el-input v-model.trim="temp.strSpare4" :maxlength="50" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="一户一码(点击展开更多可填项)" name="9">
                  <el-row v-for="(item, index2) in temp.cardItems" v-show="item.cardType===7" :key="index2" :gutter="16" class="row-box">
                    <el-col :span="8">
                      <el-form-item label="一户一码卡号:" prop="" style="width: 95%; margin-left: 15px;">
                        <el-input v-model.trim="item.cardNo" disabled />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-button type="danger" @click="removeCardItems(index2)">解绑</el-button>
                    </el-col>
                  </el-row>
                </el-collapse-item>
              </el-collapse>
            </el-form>
            <location ref="location" />
            <salesman ref="salesman" :tree-data="treeData" />
          </div>
        </el-tab-pane>
        <el-tab-pane name="invoice">
          <span slot="label"><i class="el-icon-money" /> 发票信息</span>
          <invoice
            v-if="flag"
            ref="invoice"
            :csm-lerel="csmLerel"
            :customer-type-map="customerTypeMap"
            :new-from-map="newFromMap"
            :csm-status-map="csmStatusMap"
            :csm-level-map="csmLevelMap"
            :csm-new-type-map="csmNewTypeMap"
            :acc-csmcard-card-status-map="accCsmcardCardStatusMap"
            :temp="temp"
            :invocie01="invocie01"
            :invocie02="invocie02"
          />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="success(1)">
          {{ type==='edit'?'保存':'   保存并审核' }}
        </el-button>
      </div>
    </el-dialog>
    <chooseCsmGroup ref="chooseCsmGroup" :group-type-map="groupTypeMap" />
    <groupInCsm ref="groupInCsm" :group-type-map="groupTypeMap" :csm-status-map="csmStatusMap" :csm-type-map="csmTypeMap" :sub-type-all-list="subTypeAllList" />
  </div>
</template>

<script>
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryCsmLevelMap, querySubTypeMap, queryMap, queryAddCsmDefaultData, customerUpdate, queryCsmInfoById, customerattachUpload, customerattachmentDelete, selectAreaCode, queryOrgCode, customerAttachment, queryQiniuyunUploadToken, queryGasTankList,
           processSettingDetail, csmgroupcode, customerselectYYZHList, deleteAddressCheck, checkExistByPhone, realNameConfig, getOcrData } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Invoice from './Invoice'
  import { trim, isPhone, isWildPhone } from '@/utils'
  import { defaultPaymentMethodMap, csmFromPlatMap, isPickUpMap } from '@/utils/map'
  import { getLocalSearch } from '@/utils/BMap'
  import * as qiniu from 'qiniu-js'
  import Location from './Location'
  import moment from 'dayjs'
  import Salesman from './Salesman'
  import watermark from '@/utils/watermark'
  import compress from '@/utils/compress'
  import chooseCsmGroup from './chooseCsmGroup'
  import groupInCsm from './groupInCsm'

  export default {
    name: 'edit-csm',
    components: {
      Invoice, Location, Salesman, chooseCsmGroup, groupInCsm
    },
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector('.el-autocomplete-suggestion__list')
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition =
                listDom.offsetHeight -
                wrapDom.offsetHeight +
                37 -
                0.3 -
                wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    props: {
      parentFetchData: {
        type: Function
      },
      groupTypeMap: {
        type: Array,
        require: true
      }
    },
    data() {
      // const validatePhone = (rule, value, callback) => {
      //   if (isNaN(Number(value))) {
      //     callback(new Error('请输入数字'))
      //   }
      //   callback()
      // }
      const validateIdNum = (rule, value, callback) => {
        if (value) {
          if (!(/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(value))) {
            callback(new Error('请输入正确的身份证号'))
          }
          if (this.type === 'edit' && value !== this.sfzh) {
            if (this.getAge(value) < 16) {
              callback(new Error('该用户未满16周岁，不能开户购气'))
            }
          }
        }
        callback()
      }
      return {
        sfzh: '',
        disabledPaymentMethod: false,
        disabledSettlementType: false,
        cardItems: [],
        activeTabName: 'customer',
        index: 1,
        type: 'edit',
        treeData: [],
        customerTypeMap: [],
        newFromMap: [],
        csmStatusMap: [],
        csmLevelMap: [],
        csmNewTypeMap: [],
        accCsmcardCardStatusMap: [],
        cardTypeMap: [],
        goodsList: [],
        flag: false, // 解决发票信息组件打开时默认数据异常的问题
        invocie01: [],
        invocie02: [],
        csmLerel: null,
        ck: 0,
        visible: false,
        allMap: {},
        // temp: {}
        temp: {
          area: [],
          csmName: '',
          csmCode: '',
          csmType: '',
          csmRgPhone: '',
          subType: '',
          openAccountPhone: '',
          gasNature: '',
          contact: '',
          orgSNNo: '',
          zzbh: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: moment(),
          contractNumber: '',
          decimalSpare2: '',
          intSpare2: '',
          remark: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: '',
          csmRgAddress: '', // 地址
          addressItems: [],
          phoneItems: [],
          cardItems: [],
          groupCode: '',
          groupName: '',
          groupType: '',
          licenseName: '',
          licenseUserName: ''
        },
        tempObj: {},
        activeNames: ['1', '2', '3', '4', '5', '6', '7'],
        baseUrl: 'http://image.haoyunqi.com.cn/',
        csmTypeList: [],
        subTypeList: [],
        subTypeAllList: [],
        decimalDisabled: true,
        cuindex: '',
        cascaderKey: 0,
        cardTypeAll: [],
        cardTypes: [],
        cardTypeAllList: [],
        csmCode: '',
        csmId: 0,
        customerLerel: 0,
        optFlag: undefined,
        cardInfo_temp: null, // 临时保存过滤的证件列表中身份证类型数据
        customerFromPlatMap: [],
        customerQualityMap: [],
        csmTypeMap: [],
        newTypeMap: [],
        paymentMethodMap: [],
        settlementTypeMap: [],
        defaultPaymentMethodMap,
        csmFromPlatMap,
        isPickUpMap,
        currentOrg: null,
        currentSalesman: null,
        point: null,
        rules: {
          csmType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
          csmCode: [
            { required: true, message: '请输入户号', trigger: 'change' },
            { max: 20, message: '户号长度不能超过20', trigger: 'change' }
          ],
          csmName: [
            { required: true, message: '请输入客户名称', trigger: 'change' },
            { max: 30, message: '客户名称不能超过30', trigger: 'change' }
          ],
          sfzName: [{ required: true, message: '请输入身份证姓名', trigger: 'change' }],
          subType: [{ required: true, message: '请选择用气性质', trigger: 'change' }],
          openAccountPhone: [{ required: true, message: '请输入开户电话', trigger: 'blur' },
                             { min: 11, max: 11, message: '请输入11位的手机号码', trigger: 'blur' }],
          sfzh: [
            { required: true, message: '请输入身份证号', trigger: 'change' },
            { validator: validateIdNum, trigger: 'blur' }
          ],
          sfzAddress: [
            { required: true, message: '请输入身份证地址', trigger: 'change' },
            { max: 150, message: '身份证地址长度不能超过150', trigger: 'change' }
          ],
          zzbh: [
            { required: true, message: '请输入证件号码', trigger: 'change' },
            { max: 18, message: '证件号码长度不能超过18', trigger: 'change' }
          ],
          contact: [
            { required: true, message: '请输入联系人', trigger: 'change' },
            { max: 30, message: '联系人长度不能超过30', trigger: 'change' }
          ],
          csmPhone: [
            { required: true, message: '请输入联系人电话', trigger: 'change' },
            // { validator: validatePhone, trigger: 'change' },
            { min: 8, max: 13, message: '请输入8 到 13 位数字', trigger: 'blur' }
          ],
          salesmanName: [{ required: false, message: '请选择销售人员', trigger: 'change' }],
          area: [{ required: true, message: '请输入省市区', trigger: 'change' }],
          csmAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
          doorplate: [{ required: true, message: '请输入门牌号', trigger: 'change' }],
          csmFloor: [{ required: true, message: '请输入楼层', trigger: 'change' }],
          orgSNNo: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
          groupCode: [{ required: true, message: '请输入客户组号', trigger: 'change' }],
          groupName: [{ required: true, message: '请输入客户组名称', trigger: 'change' }],
          groupType: [{ required: true, message: '请选择客户组类型', trigger: 'change' }],
          groupContact: [{ required: true, message: '请输入联系人', trigger: 'change' }],
          groupContactPhone: [{ required: true, message: '请输入联系电话', trigger: 'change' }]
        },
        addressProps: {
          lazy: true,
          checkStrictly: false,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then((res) => {
                const nodes = res.data.map(item => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        },
        addressInfo: {
          page_num: 0,
          page_size: 10
        },
        addIcon: require('../../../../assets/add.png'),
        removeIcon: require('../../../../assets/remove.png'),
        box: [],
        newBox: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        fileList: [],
        limit: 3,
        groupCsmTotal: 0,
        groupCsmTag: 0,
        relevanceGroup: true,
        tipsShow: false,
        realNameConfig: ''
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'userInfo',
        'corpSettingData'
      ])
    },
    async created() {
      console.log(!((this.userInfo.utype & 4) > 0 && (this.userInfo.utype & 64) > 0) && (this.userInfo.utype & 1) === 0)
      console.log((this.userInfo.utype & 68) <= 0)
      console.log((this.userInfo.utype & 1) <= 0)
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res, res1, res2, res3, res4, res5] = await Promise.all([
          querySubTypeMap({ }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerFromPlat' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerNewType' }),
          mergeAsyncFunc(queryMap, { enumName: 'AccCsmcardCardStatus' })])
        this.customerTypeMap = res1.data // 客户类型
        this.newFromMap = res2.data // 客户来源
        this.csmStatusMap = res3.data // 客户状态
        this.csmNewTypeMap = res4.data // 开户类型
        this.accCsmcardCardStatusMap = res5.data // 充值卡状态
        this.subTypeAllList = res.data
      },
      // 证件类型
      async getDefaultData() {
        const res = await queryAddCsmDefaultData({
          csmCode: this.temp.csmCode,
          audit: 0
        })
        this.allMap = res.data
        this.cardTypeMap = JSON.parse(res.data.cardType)
        if (this.cardTypeMap.length) {
          this.cardTypeMap = this.cardTypeMap.filter(item => item.value !== 3)
        }
      },
      // 查询客户等级枚举
      async getCsmLevelMap() {
        const res = await mergeAsyncFunc(queryCsmLevelMap)
        this.csmLevelMap = JSON.parse(res.data.customerQuality)
        this.csmLerel = Number(res.data.csmLerel)
      },
      async processSettingDetail() {
        const res = await processSettingDetail({})
        if (res.data) {
          // 企业端未启用实名制强制上传身份证
          if ((res.data.realNameEffectChannel & 4) !== 4) {
            this.rules.sfzName[0].required = false
            this.rules.sfzh[0].required = false
            this.rules.sfzAddress[0].required = false
          } else {
            this.rules.sfzName[0].required = true
            this.rules.sfzh[0].required = true
            this.rules.sfzAddress[0].required = true
          }
          if (res.data.sp1 >> 2 & 0x01) {
            this.rules.openAccountPhone[0].required = true
          } else {
            this.rules.openAccountPhone[0].required = false
          }
        }
      },
      async open(query, query01, query02, type) {
        const queryClone = JSON.parse(JSON.stringify(query))
        queryClone.data.addressItems.forEach((item) => {
          if (item.isMain === 1) {
            item.isMain = true
          } else {
            item.isMain = false
          }
        })
        await Promise.all([this.getTreeData(), this.queryOptionsMap(), this.getCsmLevelMap(), this.getDefaultData()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.reset()
          this.processSettingDetail()
          this.activeTabName = 'customer'
          if (query) {
            this.temp = Object.assign(this.temp, queryClone.data)
            this.gasTankList()
            // if (this.temp.newType === 1) {
            //   this.goodsList = this.temp.ownerBottleInfoList
            // } else {
            //   this.gasTankList()
            // }
            this.sfzh = this.temp.sfzh
            if (!this.temp.gasNature) this.temp.gasNature = ''
            console.log('this.temp', this.temp)
          }
          if (query01) {
            this.invocie01 = Object.assign(this.invocie01, query01.data)
          }
          if (query02) {
            this.invocie02 = Object.assign(this.invocie02, query02.data)
          }
          this.flag = true
          this.type = type // 判断是审核还是编辑
          this.initData()
          this.index++
        })
      },
      // 获取商品列表
      async gasTankList() {
        const res = await queryGasTankList({ orgId: this.userInfo.orgId })
        var list = []
        for (var i = 0; i < res.data.length; i++) {
          var goods = res.data[i]
          if ((goods.gdStatus & 1 << 2) > 0) {
            list.push(goods)
          }
        }
        this.goodsList = list
        this.goodsList.forEach((item, index) => {
          this.$set(this.goodsList[index], 'goodsCount', 0)
        })
        if (this.temp.newType === 1) {
          this.temp.ownerBottleInfoList.forEach((item) => {
            this.goodsList.forEach((item2) => {
              if (item.goodsName === item2.goodsName) {
                item2.goodsCount = item.goodsCount
              }
            })
          })
        }
      },
      async depositRegister() {
        this.visible = false
        await this.$refs.normalReceiptsAdd.open()
      },
      changeCsmType(csmType) {
        this.temp.subType = ''
        this.temp.subTypeList = []
        this.getSubTypeMap(csmType)
      },
      async getSubTypeMap(csmType) {
        const res = await querySubTypeMap({ csmType })
        this.subTypeList = res.data
        this.getSZRealNameConfig()
      },
      subTypeChange() {
        this.getSZRealNameConfig()
      },
      // 宿州实名制配置
      async getSZRealNameConfig() {
        this.$refs.dataForm.clearValidate()
        const params = {
          csmType: this.temp.csmType,
          subType: this.temp.subType
        }
        if (!(params.csmType && params.subType)) return
        const res = await realNameConfig(params)
        if (res && res.data) {
          this.realNameConfig = res.data
          this.rules.openAccountPhone[0].required = false
          this.rules.sfzName[0].required = false
          this.rules.sfzh[0].required = false
          this.rules.sfzAddress[0].required = false
          this.rules.zzbh[0].required = false
          if (res.data === 1) {
            this.rules.sfzName[0].required = true
            this.rules.sfzh[0].required = true
            this.rules.sfzAddress[0].required = true
          }
          if (res.data === 2) {
            this.rules.zzbh[0].required = true
          }
          if (res.data === 3) {
            this.rules.sfzName[0].required = true
            this.rules.sfzh[0].required = true
            this.rules.sfzAddress[0].required = true
            this.rules.zzbh[0].required = true
          }
        }
      },
      paymentMethodChange(defaultPaymentMethod) {
        if (defaultPaymentMethod === 16) {
          this.temp.settlementType = 2
          this.decimalDisabled = false
        }
        if (defaultPaymentMethod === 1) {
          this.temp.settlementType = 1
          this.decimalDisabled = true
        }
      },
      settlementTypeChange(settlementType) {
        if (settlementType === 2) {
          this.temp.defaultPaymentMethod = 16
          this.decimalDisabled = false
        } else {
          this.temp.defaultPaymentMethod = 1
          this.decimalDisabled = true
        }
      },

      // 选择级联框
      selectCascader(val) {
        console.log(val)
      },
      async initData() {
        this.getSubTypeMap(this.temp.csmType)
        if (!this.temp.subType) {
          this.$set(this.temp, 'subType', '')
        }
        await this.getQiniuyunUploadToken()
        this.cardTypeAll = JSON.parse(this.allMap.cardType)
        this.cardTypeAll = this.cardTypeAll.filter(item => item.value !== 7)
        this.cardTypes = this.cardTypeAll
        this.cardTypeAllList = JSON.parse(this.allMap.cardTypeAllList)
        this.ck = Number(this.allMap.ck)
        this.csmCode = this.allMap.csmCode
        // this.csmLerel = Number(this.allMap.csmLerel)
        this.csmTypeMap = JSON.parse(this.allMap.customerType)
        this.customerFromPlatMap = JSON.parse(this.allMap.customerFromPlat)
        this.customerQualityMap = JSON.parse(this.allMap.customerQuality)
        this.newTypeMap = JSON.parse(this.allMap.newType)
        this.paymentMethodMap = JSON.parse(this.allMap.paymentMethod)
        this.settlementTypeMap = JSON.parse(this.allMap.settlementType)
        if (this.temp.settlementType === 2) {
          this.settlementTypeMap = this.settlementTypeMap.filter(item => {
            if (item.value === 2) return item
          })
        }
        if (this.temp.settlementType === 2 && this.temp.cardCount > 0) {
          this.paymentMethodMap = this.paymentMethodMap.filter(item => {
            if (item.value === 16 || item.value === 256) return item
          })
        }
        if (!this.temp.unCheckQuality) this.temp.unCheckQuality = '' // 解开后会造成没有客户等级默认显示0
        if (!this.temp.defaultPaymentMethod) this.temp.defaultPaymentMethod = null // 解开后会造成没有客户支付方式默认显示0
        if (this.temp.defaultPaymentMethod === 16) this.decimalDisabled = false
        // 详细地址
        const mainAddress = this.temp.addressItems.find(l => l.isMain)
        if (mainAddress) {
          this.temp.csmFloor = mainAddress.csmFloor
        } else {
          this.temp.csmFloor = 1
        }
        if (this.temp.addressItems) {
          this.temp.addressItems.forEach((item, index) => {
            item.rowId = Symbol('rowId')
            this.$set(this.temp.addressItems[index], 'area', [])
            if (item.provinceCode) {
              item.area.push(item.provinceCode)
            }
            if (item.cityCode) {
              item.area.push(item.cityCode)
            }
            if (item.countryCode) {
              item.area.push(item.countryCode)
            }
            if (item.streetCode) {
              item.area.push(item.streetCode)
            }
            if (this.temp.phoneItems) {
              this.temp.phoneItems.forEach((item2, index2) => {
                if (item2.csmPhone === item.csmPhone) {
                  const csmPhoneId = item2.csmPhoneId
                  this.temp.phoneItems[index2] = this.temp.addressItems[index]
                  this.temp.phoneItems[index2].disabled = true
                  this.temp.phoneItems[index2].csmPhoneId = csmPhoneId
                }
              })
            }
          })
        }
        if (this.temp.cardItems) {
          const qiniuData = { // 这里是直接绑定data的值
            key: '', // 图片名字处理
            token: this.token, // 七牛云token
            data: {},
            bucket: ' '
          }
          this.temp.cardItems.forEach((item, index) => {
            this.$set(this.temp.cardItems[index], 'fileList', [])
            this.$set(this.temp.cardItems[index], 'qiniuData', qiniuData)
            if (item.cardType === 4) {
              this.$set(this.temp, 'zzbh', item.cardNo)
            }
          })
        }
        this.temp.deleteFileList = []
        this.getData()
        if (this.temp.defaultPaymentMethod === 16 && this.temp.cardCount > 0) {
          this.paymentMethodMap = this.paymentMethodMap.filter(item => {
            if (item.value === 16 || item.value === 256) return item
          })
          this.disabledPaymentMethod = false
          this.disabledSettlementType = true
          return
        }
        if (this.temp.defaultPaymentMethod !== 16 && this.temp.defaultPaymentMethod !== 256) {
          this.paymentMethodMap = this.paymentMethodMap.filter(item => {
            if (item.value !== 16 && item.value !== 256) return item
          })
          this.settlementTypeMap = this.settlementTypeMap.filter(item => {
            if (item.value !== 2) return item
          })
          this.disabledPaymentMethod = false
          this.disabledSettlementType = false
        } else {
          this.disabledPaymentMethod = true
          this.disabledSettlementType = true
        }
        this.searchCsmgroup()
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.token = res.data
      },
      async getData() {
        const res = await customerAttachment({ csmCode: this.temp.csmCode })
        this.cardList = res.data.cardItems
        this.temp.cardItems.forEach((item, index) => {
          if (!item.cardType) {
            item.cardType = ''
          }
          this.cardList.forEach((item2) => {
            if (item.cardNo === item2.cardNo) {
              if (item2.picInfos) {
                item2.picInfos = item2.picInfos.map(item => {
                  return {
                    name: item.sourceName,
                    uid: item.id,
                    upload: true,
                    url: item.url ? this.baseUrl + item.url : ''
                  }
                })
                item2.picInfos.forEach((item3) => {
                  this.temp.cardItems[index].fileList.push(item3)
                })
              }
            }
          })
        })
      },
      // 获取客户编号
      async getCsmCode() {
        const res = await queryOrgCode({
          codeType: 2
        })
        this.temp.csmCode = res.data
      },
      // 查看相关客户
      viewCsm() {
        this.$refs.groupInCsm.open(this.temp)
      },
      // 获取客户组编号
      async getGroupcode() {
        const res = await csmgroupcode({})
        this.$set(this.temp, 'groupCode', res.data)
        this.$set(this.temp, 'groupName', '')
        this.$set(this.temp, 'groupType', '')
        this.$set(this.temp, 'groupContact', '')
        this.$set(this.temp, 'groupContactPhone', '')
      },
      // 选择客户组
      async chooseGroup() {
        const res = await this.$refs.chooseCsmGroup.open()
        console.log('详细信息', res)
        this.$set(this.temp, 'groupCode', res.groupInfo.groupCode)
        this.$set(this.temp, 'groupName', res.groupInfo.groupName)
        this.$set(this.temp, 'groupType', res.groupInfo.groupType)
        this.$set(this.temp, 'groupContact', res.groupInfo.groupContact)
        this.$set(this.temp, 'groupContactPhone', res.groupInfo.groupContactPhone)
      },
      // 关联组
      relevanceGroupChange(value) {
        if (!value) {
          this.rules.groupCode[0].required = false
          this.rules.groupName[0].required = false
          this.rules.groupType[0].required = false
          this.rules.groupContact[0].required = false
          this.rules.groupContactPhone[0].required = false
        } else {
          this.rules.groupCode[0].required = true
          this.rules.groupName[0].required = true
          this.rules.groupType[0].required = true
          this.rules.groupContact[0].required = true
          this.rules.groupContactPhone[0].required = true
        }
      },
      // 获取证件编号
      async getCardNo(index) {
        const res = await queryOrgCode({
          codeType: 18
        })
        this.temp.cardItems[index].cardNo = res.data
        if (this.temp.cardItems[index].cardType === 4) {
          this.temp.zzbh = res.data
        }
      },
      async searchCsmgroup(value) {
        if (this.temp.zzbh) {
          const res = await customerselectYYZHList({ cardNo: this.temp.zzbh, csmCode: this.temp.csmCode, currentPage: 1, pageSize: 10 })
          if (res.data) {
            this.groupCsmTotal = res.data.total
            this.groupCsmTag = res.data.tag
            this.tipsShow = true
          }
        }
      },
      zzbhChange(value) {
        let has = false
        this.temp.cardItems.forEach((item) => {
          if (item.cardType === 4) {
            item.cardNo = value
            has = true
          }
        })
        if (!has) {
          if (this.temp.cardItems.length === 1 && !this.temp.cardItems[0].cardNo) {
            this.temp.cardItems = [{
              cardType: 4,
              cardNo: value,
              csmId: this.temp.csmId,
              qiniuData: { // 这里是直接绑定data的值
                key: '', // 图片名字处理
                token: this.token, // 七牛云token
                data: {},
                bucket: ' '
              },
              fileList: []
            }]
          } else {
            this.temp.cardItems.push(
              {
                cardType: 4,
                cardNo: value,
                csmId: this.temp.csmId,
                qiniuData: { // 这里是直接绑定data的值
                  key: '', // 图片名字处理
                  token: this.token, // 七牛云token
                  data: {},
                  bucket: ' '
                },
                fileList: []
              }
            )
          }
        } else {
          this.temp.cardItems.forEach((item) => {
            if (item.cardType === 4) {
              item.cardNo = value
            }
          })
        }
      },
      // 点击获取销售员
      async openSalesman() {
        const res = await this.$refs.salesman.open()
        this.currentSalesman = res
        this.$set(this.temp, 'salesmanName', res.userName)
        this.$set(this.temp, 'salesman', res.userId)
      },
      // 清除销售员
      clearSalesman() {
        this.$set(this.temp, 'salesmanName', '')
        this.currentSalesman = null
      },
      csmNameChange(value) {
        // this.temp.contact = value
      },
      visibleChange(visible) {
        if (!visible) {
          console.log('blur')
          this.temp.addressItems.forEach((item, index) => {
            const name = 'cascader' + index
            const address = this.$refs[name][0].getCheckedNodes()[0]
            if (address) {
              const pathNodes = address.pathNodes
              if (pathNodes.length < 4) {
                this.$message.warning('请选择省市区街道')
                this.$refs[name][0].$refs.panel.clearCheckedNodes()
                this.temp.addressItems[index].area = []
                this.temp.addressItems[index].provinceName = ''
                this.temp.addressItems[index].provinceCode = ''
                this.temp.addressItems[index].cityName = ''
                this.temp.addressItems[index].cityCode = ''
                this.temp.addressItems[index].countryName = ''
                this.temp.addressItems[index].countryCode = ''
                this.temp.addressItems[index].streetName = ''
                this.temp.addressItems[index].streetCode = ''
              }
            }
          })
        }
      },
      // 格式化金额
      formatInput(e) {
        if (e.target.value) {
          e.target.value = (e.target.value * 1).toFixed(2)
        }
      },
      async success() {
        this.type === 'audit' ? this.temp.csmStatus = 2 : ''
        const code = {
          ...this.temp,
          licenseCode: this.temp.zzbh
        }
        code.cardItems = this.temp.cardItems.map(item => {
          return {
            ...item,
            picIds: item.fileList.filter(file => file.upload).map(item1 => item1.uid).join(',')
          }
        })
        const invoice_enterprise_list = this.$refs.invoice.tableData01.data.concat(this.$refs.invoice.tableData.data)
        for (let i = 0; i < invoice_enterprise_list.length; i++) {
          const phone = invoice_enterprise_list[i].taxPhone
          const invoiceCorp = invoice_enterprise_list[i].invoiceCorp
          const taxType = invoice_enterprise_list[i].taxType
          if (trim(invoiceCorp) === '') {
            this.$message.error('抬头名称不能为空')
            return false
          }

          if (taxType === 1 && invoice_enterprise_list[i].taxRegNumber === '') {
            this.$message.error('抬头名称' + invoiceCorp + '的纳税人识别号不能为空')
            return false
          }

          if (taxType === 1 && invoice_enterprise_list[i].taxAddress === '') {
            this.$message.error('抬头名称' + invoiceCorp + '的单位地址不能为空')
            return false
          }

          if (taxType === 1 && invoice_enterprise_list[i].taxPhone === '') {
            this.$message.error('抬头名称' + invoiceCorp + '的电话号码不能为空')
            return false
          }

          if ((taxType === 1) || (taxType === 2 && invoice_enterprise_list[i].taxPhone !== '')) {
            if (!isPhone(phone) && !isWildPhone(phone)) {
              this.$message.error('电话号码' + phone + '的格式不正确')
              return false
            }
          }

          if (taxType === 1 && invoice_enterprise_list[i].taxBank === '') {
            this.$message.error('抬头名称' + invoiceCorp + '的开户银行不能为空')
            return false
          }

          if (taxType === 1 && invoice_enterprise_list[i].taxAccountNumber === '') {
            this.$message.error('抬头名称' + invoiceCorp + '的银行账号不能为空')
            return false
          }
        }
        code.invoiceItems = invoice_enterprise_list
        let messageInfo = ''
        const csmInfo = await queryCsmInfoById({
          csmId: this.temp.csmId
        })
        if (csmInfo.data.qualityStatus === 1 && this.temp.unCheckQuality > 0) {
          messageInfo = '有待审核的等级申请，请审批后再调整等级，确认保存客户信息？'
        } else {
          messageInfo = '确认保存客户信息？'
        }
        code.isForceDoorplate = 1
        console.log('address')
        console.log(code.addressItems)
        code.addressItems.forEach((item, index) => {
          if (item.isMain) {
            item.isMain = 1
          } else {
            item.isMain = 0
          }
          const name = 'cascader' + index
          const address = this.$refs[name][0].getCheckedNodes()[0]
          if (address) {
            const pathNodes = address.pathNodes
            switch (pathNodes.length) {
            case 1:
              item.provinceName = pathNodes[0].label
              item.provinceCode = pathNodes[0].value
              break
            case 2:
              item.provinceName = pathNodes[0].label
              item.provinceCode = pathNodes[0].value
              item.cityName = pathNodes[1].label
              item.cityCode = pathNodes[1].value
              break
            case 3:
              item.provinceName = pathNodes[0].label
              item.provinceCode = pathNodes[0].value
              item.cityName = pathNodes[1].label
              item.cityCode = pathNodes[1].value
              item.countryName = pathNodes[2].label
              item.countryCode = pathNodes[2].value
              break
            case 4:
              item.provinceName = pathNodes[0].label
              item.provinceCode = pathNodes[0].value
              item.cityName = pathNodes[1].label
              item.cityCode = pathNodes[1].value
              item.countryName = pathNodes[2].label
              item.countryCode = pathNodes[2].value
              item.streetName = pathNodes[3].label
              item.streetCode = pathNodes[3].value
              break
            }
          } else {
            item.provinceName = ''
            item.provinceCode = ''
            item.cityName = ''
            item.cityCode = ''
            item.countryName = ''
            item.countryCode = ''
            item.streetName = ''
            item.streetCode = ''
          }
          if (item.csmFloor) {
            if (isNaN(Number(item.csmFloor))) {
              item.csmFloor = ''
            }
          }
        })
        code.phoneItems.forEach((item) => {
          item.cpStatus = 2
        })
        if (code.newType === 1) {
          code.ownerBottleInfoList = []
          this.goodsList.forEach((item) => {
            const obj = {
              csmId: code.csmId,
              goodsId: item.goodsId,
              goodsName: item.goodsName,
              goodsCount: item.goodsCount,
              specCode: item.specCode
            }
            code.ownerBottleInfoList.push(obj)
          })
        }
        if (this.relevanceGroup) {
          code.groupCode = this.temp.groupCode
          code.groupName = this.temp.groupName
          code.groupType = this.temp.groupType
          code.groupContact = this.temp.groupContact
          code.groupContactPhone = this.temp.groupContactPhone
        }
        this.$confirm(messageInfo, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          this.$refs.dataForm.validate(async valid => {
            if (!valid) this.$message.warning('请将必填项信息填完')
            else {
              if (this.groupCsmTag > 0 && code.subType !== 9) {
                this.$confirm('使用此营业执照开户后，客户性质为餐饮（连锁）', '提示', {
                  type: 'info'
                }).then(async() => {
                  code.subType = 9
                  const res = await customerUpdate(code)
                  if (res.success) {
                    this.parentFetchData({})
                    if (this.temp.deleteFileList && this.temp.deleteFileList.length > 0) {
                      await this.deleteImg()
                    }
                    this.saveImg()
                    this.resolve()
                  }
                }).catch(() => {})
              } else {
                const res = await customerUpdate(code)
                if (res.success) {
                  this.parentFetchData({})
                  if (this.temp.deleteFileList && this.temp.deleteFileList.length > 0) {
                    await this.deleteImg()
                  }
                  this.saveImg()
                  this.resolve()
                }
              }
            }
          })
        }).catch(() => {

        })
      },
      saveImg() {
        const paramJson = []
        this.temp.cardItems.forEach((item) => {
          if (item.fileList && item.fileList.length > 0) {
            const obj = {
              csmId: this.temp.csmId,
              cardNo: item.cardNo,
              cardType: item.cardType,
              sysAttachmentList: []
            }
            item.fileList.forEach((item2) => {
              if (item2.key) {
                obj.sysAttachmentList.push(
                  {
                    sourceName: item2.key.split('.')[0],
                    suffix: item2.key.split('.')[1],
                    url: item2.key,
                    size: item2.fsize
                  }
                )
              }
            })
            paramJson.push(obj)
          }
        })
        if (paramJson.length > 0) {
          customerattachUpload({ paramJson: paramJson }).then(() => {
            this.visible = false
          })
        } else {
          this.visible = false
        }
      },
      deleteImg() {
        this.temp.deleteFileList.forEach((item) => {
          customerattachmentDelete({
            csmId: this.temp.csmId,
            cardType: item.cardType,
            cardNo: item.cardNo,
            picId: item.picId
          }).then(() => {})
        })
      },
      handleClick(tab) {
        if (tab.name === 'contaction') {
          this.$refs.editContaction.tableData01.data = this.temp.phoneItems
          this.$refs.editContaction.tableData02.data = this.temp.addressItems
        }
      },
      // 定位
      async location(item, index) {
        if (item.area.length !== 4) {
          this.$message.warning('请先选择省市区街道信息，再填写详细地址定位')
          return
        }
        const res = await this.$refs.location.open(item)
        // 处理详细地址
        this.temp.csmAddress = res.address
        this.temp.addressItems[index].csmAddress = res.address
        this.temp.addressItems[index].latitude = res.point.lat
        this.temp.addressItems[index].longitude = res.point.lng
        this.csmAddressChange(index)
      },
      getLoad() {
        console.log('i am load')
        this.addressInfo.page_num++
        this.$refs.suggestionInput.fetchSuggestions()
      },
      async queryAddressSearch(queryString, cb, index) {
        this.getAddressSuggestionList(cb, index)
      },
      // 输入建议
      async getAddressSuggestionList(cb, index) {
        let queryString = ''
        if (this.temp.addressItems[index].provinceName) {
          queryString += this.temp.addressItems[index].provinceName
        }
        if (this.temp.addressItems[index].cityName) {
          queryString += this.temp.addressItems[index].cityName
        }
        if (this.temp.addressItems[index].countryName) {
          queryString += queryString += this.temp.addressItems[index].cityName
        }
        if (this.temp.addressItems[index].csmAddress) {
          queryString += queryString += this.temp.addressItems[index].csmAddress
        }
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: queryString,
          city: this.temp.addressItems[index].cityName
        }
        const res = await getLocalSearch(params)
        console.log(res)
        if (res && res.results && res.results.length > 0) {
          let list = []
          list = res.results.map(item => ({
            value: item.name || '',
            location: item.location,
            address: item.address || '',
            adcode: item.adcode || '',
            province: item.province || '',
            city: item.city || '',
            area: item.area || ''
          }))
          if (this.temp.addressItems[index].area && this.temp.addressItems[index].countryName) {
            list = list.filter(item => (item.area && item.area.includes(this.temp.addressItems[index].countryName)) || (item.area === ''))
          }
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionInput.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      // 地址模糊匹配
      handleSelect(item, index) {
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          this.temp.addressItems[index].point = [latAndLon.lat, latAndLon.lng]
        }
      },
      csmAddressChange(index) {
        setTimeout(() => {
          const csmAddress = this.temp.addressItems[index].csmAddress
          this.temp.addressItems.forEach((item, index2) => {
            if (item.csmAddress === csmAddress && index !== index2) {
              this.temp.addressItems[index].csmAddress = ''
              this.$message.warning('该地址已存在')
            }
          })
        }, 500)
      },
      // 选择所属机构
      selectTreeChange(value, idx) {
        this.currentOrg = value
        this.temp.addressItems[idx].orgId = this.currentOrg.orgId
        this.temp.addressItems[idx].orgName = this.currentOrg.orgName
      },
      reset() {
        this.temp = {
          area: [],
          csmName: '',
          csmCode: '',
          csmType: '',
          csmRgPhone: '',
          openAccountPhone: '',
          subType: '',
          gasNature: '',
          contact: '',
          orgSNNo: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          zzbh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: moment(),
          contractNumber: '',
          decimalSpare2: '',
          intSpare2: '',
          remark: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: '',
          csmRgAddress: '', // 地址
          addressItems: [],
          phoneItems: [],
          cardItems: [],
          groupCsmTotal: 0,
          groupCsmTag: 0,
          relevanceGroup: true,
          tipsShow: false,
          licenseName: '',
          licenseUserName: ''
        }
        this.activeNames = ['1', '2', '3', '4', '5', '6', '7']
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      // 添加联系人
      addLinkMan() {
        this.temp.phoneItems.push({ contact: '', csmPhone: '', cpStatus: 2, isMain: false })
      },
      // 移除联系人
      removeLinkMan(index) {
        this.temp.phoneItems.splice(index, 1)
      },
      // 添加地址
      addCsminfo(index) {
        const rowId = Symbol('rowId')
        const item = { contact: '', csmPhone: '', area: [], csmAddress: '', csmFloor: '', showInput: false, rowId: rowId }
        item['cascader' + index + 1] = 0
        this.temp.addressItems.push(item)
        // this.temp.phoneItems.push({ contact: '', csmPhone: '', rowId: rowId })
        this.temp.phoneItems.push(this.temp.addressItems[this.temp.addressItems.length - 1])
        this.temp.phoneItems[this.temp.phoneItems.length - 1].disabled = true
      },
      // 移除地址
      async removeCsminfo(index) {
        if (!this.temp.addressItems[index].csmId || !this.temp.addressItems[index].csmAddressId) {
          this.doRemove(index)
          return
        }
        const params = {
          csmId: this.temp.addressItems[index].csmId,
          csmAddressId: this.temp.addressItems[index].csmAddressId
        }
        const res = await deleteAddressCheck(params)
        if (res) {
          if (res.data === 0) {
            this.doRemove(index)
          }
          if (res.data === 1) {
            this.$message.error('此地址为唯一地址，不允许删除!')
          }
          if (res.data === 2) {
            this.$message.error('此地址有待完成单据，无法删除！')
          }
        }
      },
      doRemove(index) {
        this.$confirm('确定删除该地址吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            const rowId = this.temp.addressItems[index].rowId
            this.temp.addressItems.splice(index, 1)
            this.temp.addressItems.forEach((item, index) => {
              item['cascader' + index]++
            })
            this.temp.phoneItems.forEach((item, index) => {
              if (item.rowId === rowId) {
                this.temp.phoneItems.splice(index, 1)
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      // 长沙验证手机号唯一
      async verifyPhone(value) {
        if (value.length === 11) {
          await checkExistByPhone({ openAccountPhone: value, csmId: this.temp.csmId })
        }
      },
      async verifyCsmPhone(value) {
        if (value.length > 7 && value.length < 14 && value.length !== 11) {
          this.$confirm('您输入的联系人电话不是11位，确认是否继续用此号码开户?', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(async() => {}).catch(() => {})
        }
      },
      crmPhoneChange(value, rowId, index) {
        let hasRow = false
        let hasItem = false
        this.temp.phoneItems.forEach((item, index) => {
          if (item.rowId !== rowId) {
            if (item.csmPhone === value) {
              // this.$message.warning('该联系电话已存在')
              this.temp.phoneItems.splice(index, 1)
              hasItem = true
            }
          }
          if (item.rowId === rowId) {
            hasRow = true
          }
        })
        if (!hasRow) {
          if (!hasItem) {
            this.temp.phoneItems.push(this.temp.addressItems[index])
            this.temp.phoneItems[this.temp.phoneItems.length - 1].disabled = true
          }
        }
      },
      phoneChange(value, index) {
        this.temp.phoneItems.forEach((item, index2) => {
          if (index2 !== index) {
            if (item.csmPhone === value) {
              this.$alert('该联系电话已存在，请删除', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.temp.phoneItems.splice(index, 1)
                }
              })
            }
          }
        })
      },
      // 新增证件
      addCardItems() {
        const qiniuData = { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: this.token, // 七牛云token
          data: {},
          bucket: ' '
        }
        this.temp.cardItems.push({ cardType: '', cardNo: '', fileList: [], qiniuData: qiniuData })
      },
      // 移除证件
      removeCardItems(index) {
        if (this.temp.cardItems[index].cardType === 3) {
          this.cardTypes = this.cardTypeAll
          this.temp.sfzh = ''
        }
        if (this.temp.cardItems[index].cardType === 4) {
          this.temp.licenseName = ''
          this.temp.licenseUserName = ''
        }
        this.temp.cardItems.splice(index, 1)
      },
      async inputSfzh(value) {
        if (this.temp.cardItems.some(item => item.cardType === 3)) {
          this.cardTypes = this.cardTypeAll.filter(item => item.value !== 3)
          const index = this.temp.cardItems.findIndex(item => item.cardType === 3)
          this.temp.cardItems[index].cardNo = value
          return
        }
        if (this.temp.cardItems.length === 1 && this.temp.cardItems[0].cardType === '') {
          this.temp.cardItems = [{
            cardType: 3,
            cardNo: value,
            fileList: [],
            qiniuData: { // 这里是直接绑定data的值
              key: '', // 图片名字处理
              token: this.token, // 七牛云token
              data: {},
              bucket: ' '
            }
          }]
          return
        }
        const sfzhItem = {
          cardType: 3,
          cardNo: value,
          fileList: [],
          qiniuData: { // 这里是直接绑定data的值
            key: '', // 图片名字处理
            token: this.token, // 七牛云token
            data: {},
            bucket: ' '
          }
        }
        this.temp.cardItems.push(sfzhItem)
      },
      // 变更证件类型
      changeCardType(value, index) {
        // console.log(value, this.temp.cardItems[index].cardType)
        if (value) {
          if (this.temp.cardItems.some(item => item.cardType === 3)) {
            if (this.temp.cardItems[index].cardType !== 3) {
              this.cardTypes = this.cardTypeAll.filter(item => item.value !== 3)
            } else {
              this.cardTypes = this.cardTypeAll
            }
          } else {
            this.cardTypes = this.cardTypeAll
          }
          if (this.temp.cardItems.some(item => item.cardType === 4)) {
            if (this.temp.cardItems[index].cardType !== 4) {
              this.cardTypes = this.cardTypes.filter(item => item.value !== 4)
            }
          }
        }
        if (!value && this.temp.cardItems[index].cardType === 3 && this.temp.cardItems[index].cardNo) {
          this.temp.sfzh = this.temp.cardItems[index].cardNo
        }
        if (!value && this.cardTypes.some(item => item.value === 3) && this.temp.cardItems[index].cardType !== 3) {
          this.temp.sfzh = ''
        }
        if (this.cardTypes.some(item => item.value === 4) && this.temp.cardItems[index].cardType !== 4) {
          this.temp.licenseName = ''
          this.temp.licenseUserName = ''
        }
        this.temp.cardItems = [...this.temp.cardItems]
      },
      cardNoChange(value, cardType) {
        if (cardType === 4) {
          this.temp.zzbh = value
        }
        if (cardType === 3) {
          this.temp.sfzh = value
        }
      },
      isMainChange(value, csmPhone, index) {
        if (value) {
          this.temp.addressItems.forEach((item, index2) => {
            if (index !== index2) {
              this.$set(this.temp.addressItems[index2], 'isMain', false)
            }
            this.temp.phoneItems.forEach((item, index3) => {
              if (item.csmPhone !== csmPhone) {
                this.$set(this.temp.phoneItems[index3], 'isMain', false)
              }
              if (item.csmPhone === csmPhone && csmPhone) {
                this.$set(this.temp.phoneItems[index3], 'isMain', true)
              }
            })
          })
        }
      },
      // 营业执照信息
      uploadChange(file) {
        this.fileList.push(file)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleRemove(file) {
        this.fileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.fileList.splice(index, 1)
          }
        })
      },
      // 证件信息
      uploadChange2(file, index) {
        this.temp.cardItems[index].fileList.push(file)
      },
      beforeUpload(file, index) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.temp.cardItems[index].qiniuData.key = key
        return this.temp.cardItems[index].qiniuData
      },
      uploadToQiNiu(e, index) {
        const _this = this
        const file = e.file // Blob 对象，上传的文件
        const config = {
          useCdnDomain: true, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
        }
        const putExtra = {
          fname: this.temp.cardItems[index].qiniuData.key, // 文件原文件名
          params: {}, // 用来放置自定义变量
          mimeType: ['image/png', 'image/jpeg', 'image/jpg'] // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
        }
        this.changeFile(file, function(file) {
          var observable = qiniu.upload(file, _this.temp.cardItems[index].qiniuData.key, _this.temp.cardItems[index].qiniuData.token, putExtra, config)
          observable.subscribe({
            next: result => {
              // 主要用来展示进度
              console.log(result)
            },
            error: errResult => {
              // 失败报错信息'
              console.log(errResult)
              _this.$message.error('上传失败')
              const length = _this.temp.cardItems[index].fileList.length
              _this.temp.cardItems[index].fileList.splice(length - 1, 1)
            },
            complete: result => {
              // 接收成功后返回的信息
              _this.temp.cardItems[index].fileList.push(result)
              _this.temp.cardItems[index].fileList[_this.temp.cardItems[index].fileList.length - 1].url = _this.baseUrl + result.key
              if (_this.temp.cardItems[index].fileList.length === 1) {
                if (_this.temp.cardItems[index].cardType === 3) {
                  _this.getIdCardOcrData(result.key, _this.temp.cardItems[index])
                } else if (_this.temp.cardItems[index].cardType === 4) {
                  _this.getLicenseOcrData(result.key, _this.temp.cardItems[index])
                }
              }
            }
          })
        }, function() {
          _this.$message.error('压缩失败')
        })
      },
      async getIdCardOcrData(path, target) {
        const params = {
          side: 'front',
          path: path
        }
        const res = await getOcrData(params)
        if (res.data) {
          const { name, idNumber, address } = res.data
          if (name) {
            this.temp.sfzName = name
          }
          if (idNumber) {
            this.temp.sfzh = idNumber
            target.cardNo = idNumber
          }
          if (address) {
            this.temp.sfzAddress = address
          }
        }
      },
      async getLicenseOcrData(path, target) {
        const params = {
          side: 'license',
          path: path
        }
        const res = await getOcrData(params)
        if (res.data) {
          const { licenseCode, licenseName, licenseUserName } = res.data
          if (licenseCode) {
            this.temp.zzbh = licenseCode
            target.cardNo = licenseCode
          }
          if (licenseName) {
            this.temp.licenseName = licenseName
          }
          if (licenseUserName) {
            this.temp.licenseUserName = licenseUserName
          }
        }
      },
      changeFile(file, onload, onerror) {
        compress(file, 3 * 1024 * 1024, 2 * 1024 * 1024, function(_file) {
          watermark(_file, '仅供附件上传使用，他用无效', onload, onerror)
        }, onerror)
      },
      handleRemove2(file, index) {
        this.temp.cardItems[index].fileList.forEach((item, index2) => {
          if (item.uid === file.uid) {
            this.temp.cardItems[index].fileList.splice(index2, 1)
          }
        })
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      getAge(identityCard) {
        var len = (identityCard + '').length
        if (len === 0) {
          return 0
        } else {
          if ((len !== 15) && (len !== 18)) { // 身份证号码只能为15位或18位其它不合法
            return 0
          }
        }
        var strBirthday = ''
        if (len === 18) { // 处理18位的身份证号码从号码中得到生日和性别代码
          strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2)
        }
        if (len === 15) {
          strBirthday = '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
        }
        // 时间字符串里，必须是“/”
        var birthDate = new Date(strBirthday)
        var nowDateTime = new Date()
        var age = nowDateTime.getFullYear() - birthDate.getFullYear()
        // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
        if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() === birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
          age--
        }
        return age
      }
    }
  }
</script>

<style lang="scss" scoped>
.csmDialog {
  /deep/ .el-dialog {
    height: 100vh;
    margin-top: 0 !important;
  }
  /deep/.el-dialog .el-dialog__body {
    max-height: 85vh !important;
    overflow: auto;
  }
  /deep/.el-dialog .el-dialog__footer {
    padding: 10px !important;
  }
  /deep/ .el-collapse-item__header {
    padding-left: 10px;
    font-size: 16px;
    color: #38BDBD;
    border-left: 5px solid #38BDBD;
  }
  /deep/ .el-collapse-item__content {
    padding: 5px 0;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
.addCsmDialog {
  /deep/ .el-dialog {
    height: 100vh;
    margin-top: 0 !important;
  }
  /deep/.el-dialog .el-dialog__body {
    max-height: 86vh !important;
    padding: 15px 40px;
    overflow: auto;
  }
  /deep/.el-dialog .el-dialog__footer {
    padding: 10px !important;
  }
  /deep/ .el-collapse-item__header {
    height: 38px;
    padding-left: 10px;
    font-size: 14px;
    line-height: 38px;
    color: #38BDBD;
    border-left: 5px solid #38BDBD;
  }
  /deep/ .el-collapse-item__content {
    // padding: 5px 0;
    padding: 0;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .block {
    width: 100%;
  }
  .collapse {
    width: 100%;
  }
  & /deep/ .el-form-item {
    width: 100%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  & /deep/ .form-row-item {
    width: 100%;
    .el-form-item__content > .el-input {
      width: 30%;
    }
    .el-form-item__content > .el-select {
      width: 30%;
    }
  }
  .row-box {
    padding: 5px 25px 0 0;
  }
  .csminfoBox {
    position: relative;
    width: 100%;
    padding: 10px 25px 0 0;
    margin-top: 10px;
    background-color: #FAFAFA;
  }
  .icon-box {
    position: absolute;
    top: 40%;
    right: 40px;
    display: none;
  }
  .tel-box {
    width: 100%;
  }
  .bottomBtn {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
    .btn {
      margin-right: 10px;
      color: #38BDBD;
      cursor: pointer;
    }
    .danger {
      color: #F56C6C;
    }
  }
  /deep/.el-autocomplete {
    width: 100%;
  }
  .group-tips {
    padding-left: 40px;
    color: #F56C6C;
  }
}
</style>
